<script setup lang="ts">
import { ref, onMounted, toRaw } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
// 引入组件
import AddDevice from './component/add.vue';
import EditDevice from './component/edit.vue';
import BatchAdd from './component/batchAdd.vue';
import BindDeviceToScene from '@/views/alerts/scene/component/bind-device-to-scene.vue';
import { getDeviceListApi, deleteDeviceApi, DeviceModel } from "@/api/products/device";
import { useLogic } from "@/views/system/user/logic/logic";
import {getDeviceGroupOptionsApi} from "@/api/products/deviceGroup";
import { getProductOptionsApi } from "@/api/products/product";
import { handleTree } from "@/utils/tree";
import { getDeviceStatusOptions } from "@/utils/appCommon/appCommonOptions/products";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { useI18n } from "vue-i18n";

//一定要和服务端的权限名称一样
defineOptions({
  name: "device-manage"
});
const { t } = useI18n();
const pageSizeOps = ref(pageSizeOptions)

// 产品选项数据
const productOptions = ref([]);
const deviceGroupOptions = ref([]);
const deviceStatusOptions = ref([]);
const {deptTreeList,getDeptTree}  = useLogic()
onMounted(async () => {
  await getDeptTree()
  const productOptionsRes = await getProductOptionsApi()
  if(productOptionsRes.code == 0){
    productOptions.value = [
      ...productOptionsRes.data.options.map(option => ({
        val: option.val,
        label: option.label
      }))
    ];
  }
  const deviceGroupOptionsRes = await getDeviceGroupOptionsApi()
  if(deviceGroupOptionsRes.code == 0){
    deviceGroupOptions.value = handleTree(deviceGroupOptionsRes.data.options);
    console.log(toRaw(deviceGroupOptions.value))
  }
  deviceStatusOptions.value = await getDeviceStatusOptions()
})

// 搜索处理 - 增加搜索参数存储
const searchParams = ref({
  deviceNo: undefined,
  name:undefined,
  productId:undefined,
  groupId:undefined,
  status:undefined,
  deptId:undefined,
  timeRange: [],
  page:1,
  pageSize:10,
});

// 搜索字段配置 - 更新为小驼峰命名
const searchFields = ref([
  { prop: "deviceNo", name: t("products.devicePage.deviceNo"), type: "input", placeholder: t("products.devicePage.deviceNoPlaceholder") },
  { prop: "name", name: t("products.devicePage.name"), type: "input", placeholder: t("products.devicePage.namePlaceholder") },
  { prop: "productId", name: t("products.devicePage.productId"), type: "select", formOptions:productOptions},
  { prop: 'groupId', name: t("products.devicePage.groupId"), type: 'cascader', cascaderOptions: deviceGroupOptions, ops: { valueField: 'id', labelField: 'name', emitPath: false, checkStrictly: true } },
  { prop: "status", name: t("products.devicePage.type"), type: "select", formOptions: deviceStatusOptions},
  { prop: 'deptId', name: t("products.devicePage.deptId"), type: 'cascader', cascaderOptions: deptTreeList, ops: { valueField: 'id', labelField: 'name', emitPath: false, checkStrictly: true } },
  { prop: 'timeRange', name: t("buttons.timeRange"), type: 'datetimeRange', clearable: true, isHidden: false, },
]);

// 设备列表数据
const deviceList = ref<any[]>([]);
const total = ref(0);

// 加载设备列表 - 修复参数命名与搜索逻辑
const loadDeviceList = async () => {
  try {
    const params = {
      ...searchParams.value
    };

    const response = await getDeviceListApi(params);
    if (response.code === 0) {
      deviceList.value = response.data.list || [];
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || t("products.devicePage.deleteFailed"));
    }
  } catch (error) {
    total.value = 0
    deviceList.value = []
    ElMessage.error("获取设备列表失败");
    console.error("Failed to load device list:", error);
  }
};


const  handleChange = (e: any) => {
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
}
const handleSearch = async (e:any) => {
  searchParams.value.page = 1
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  await  loadDeviceList();
}
const handleReset = (e:any) => {
}

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  console.log(pageSize);
  searchParams.value.pageSize = pageSize;
  loadDeviceList();
};
const handlePaginationPageChange = (page: number) => {
  console.log(page);
  searchParams.value.page = page;
  loadDeviceList();
};

// 初始加载
onMounted(() => {
  console.log("device onMounted")
  loadDeviceList();
});

// 格式化设备类型
const formatDeviceType = (type: number) => {
 const types = [t("products.devicePage.directDevice"), t("products.devicePage.gatewayDevice"), t("products.devicePage.childDevice")];
 return types[type] || "未知";
};

// 格式化设备状态
const formatDeviceStatus = (status: number) => {
 return status === 2 ?
   `<span class="status-online">${t("products.devicePage.online")}</span>` :
   `<span class="status-offline">${t("products.devicePage.offline")}</span>`;
};

// 弹窗控制变量
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const currentDevice = ref<any>(null);
const batchAddVisible = ref(false);
// 绑定场景相关
const bindSceneDialogVisible = ref(false);
const currentBindDevice = ref<DeviceModel | any>({
  deviceNo: "",
  deptId: 0,
});

// 打开新增弹窗
const openAddDialog = () => { addDialogVisible.value = true; };
const openBatchAddDialog = () => { batchAddVisible.value = true; };
// 打开编辑弹窗
const openEditDialog = (device: any) => {
 currentDevice.value = { ...device };
 editDialogVisible.value = true;
};

// 刷新列表
const refreshList = () => { loadDeviceList(); };
// 删除设备 - 修复状态码判断
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      t("products.devicePage.deleteConfirmMsg"),
      t("products.devicePage.deleteConfirmTitle"),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning',
      }
    );

    const response = await deleteDeviceApi(id);
    if (response.code === 0) {
      ElMessage.success(t("products.devicePage.deleteSuccess"));
      refreshList();
    } else {
      ElMessage.error(response.msg || t("products.devicePage.deleteFailed"));
    }
  } catch (error: any) {
    if (error.name !== 'cancel') {
      ElMessage.error("delete fail");
      console.error("Failed to delete device:", error);
    }
  }
};
// 格式化激活状态
const formatOpenStatus = (status: number) => {
  return status === 1 ? t("products.devicePage.activated") : t("products.devicePage.notActivated");
};

const router = useRouter();
const goToDeviceConfig = (device: DeviceModel) => {
  router.push({
    path: '/configs/deviceConfig',
    query: device
  });
};

// 打开关联场景对话框
const handleBindScene = (device: DeviceModel) => {
  console.log(toRaw(device));
  currentBindDevice.value = device;
  bindSceneDialogVisible.value = true;
};

// 关联场景成功处理
const handleBindSceneSuccess = () => {
  bindSceneDialogVisible.value = false;
};
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :fields="searchFields"
          :initialValues="searchParams"
          :maxVisibleFields="3"
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>

    <!-- 按钮区 -->
    <div class="button-area">
      <el-button type="primary" icon="Plus" @click="openAddDialog">
        {{ t("products.devicePage.addDevice") }}
      </el-button>
      <el-button type="warning" icon="DocumentAdd" @click="openBatchAddDialog">
        {{ t("products.devicePage.batchAdd") }}
      </el-button>
    </div>

    <!-- 设备列表 -->
    <div class="device-list-container">
      <div v-if="deviceList.length === 0" class="empty-state">
        <el-empty :description="t('products.devicePage.noData')" />
      </div>
      <div v-else class="device-grid">
        <el-card
          v-for="device in deviceList"
          :key="device.id"
          class="device-card"
          :body-style="{ padding: '16px' }"
        >
          <div class="device-info">
            <div class="device-image">
              <img
                :src="device.image || '/images/default-device.png'"
                alt="{{ device.name }}"
                class="device-img"
              />
            </div>
            <div class="device-details">
              <h3 class="device-name">{{ device.name }}</h3>
              <div class="device-meta">
                <div class="meta-item">
                  <span class="meta-label"
                    >{{ t("products.devicePage.deviceNo") }}:</span
                  >
                  <span class="meta-value">{{ device.deviceNo }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label"
                    >{{ t("products.devicePage.productName") }}:</span
                  >
                  <span class="meta-value">{{ device.productName }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label"
                    >{{ t("products.devicePage.lastOnline") }}:</span
                  >
                  <span class="meta-value">{{ device.statusTime }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label"
                    >{{ t("products.devicePage.type") }}:</span
                  >
                  <span class="meta-value">{{
                    formatDeviceType(device.type)
                  }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label"
                    >{{ t("products.devicePage.openStatus") }}:</span
                  >
                  <span class="meta-value">{{
                    formatOpenStatus(device.openStatus)
                  }}</span>
                </div>
                <div v-if="device.type === 2" class="meta-item">
                  <span class="meta-label"
                    >{{ t("products.devicePage.parentId") }}:</span
                  >
                  <span class="meta-value">{{ device.parentId || "-" }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label"
                    >{{ t("products.devicePage.type") }}:</span
                  >
                  <span
                    class="meta-value"
                    v-html="formatDeviceStatus(device.status)"
                  ></span>
                </div>
                <div class="meta-item">
                  <span class="meta-label"
                    >{{ t("products.devicePage.lastTime") }}:</span
                  >
                  <span class="meta-value">{{ device.statusTime }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label"
                    >{{ t("products.devicePage.version") }}:</span
                  >
                  <span class="meta-value">{{ device.version || "-" }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="device-actions">
            <el-dropdown size="small">
              <el-button type="danger" size="small" plain>
                {{ t("products.devicePage.manage") }}
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openEditDialog(device)">{{
                      t("products.devicePage.edit")
                    }}</el-dropdown-item>

                  <el-dropdown-item @click="goToDeviceConfig(device)">{{
                    t("products.devicePage.config")
                  }}</el-dropdown-item>
                  <el-dropdown-item @click="handleBindScene(device)">{{
                    t("alerts.sceneOperatePage.bindScene")
                  }}</el-dropdown-item>
                  <el-dropdown-item
                    @click="handleDelete(device.id)"
                    style="margin-top: 10px; color:red"
                    >{{ t("products.devicePage.delete") }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="pageSizeOps"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handlePaginationSizeChange"
          @current-change="handlePaginationPageChange"
        />
      </div>
    </div>

    <!-- 新增弹框 -->
    <AddDevice v-model:visible="addDialogVisible" @success="refreshList" />

    <BatchAdd v-model:visible="batchAddVisible" @success="refreshList" />

    <!-- 编辑弹框 -->
    <EditDevice
      v-model:visible="editDialogVisible"
      :device="currentDevice"
      @success="refreshList"
    />
    <BindDeviceToScene
      v-model:visible="bindSceneDialogVisible"
      :device-no="currentBindDevice.deviceNo "
      :dept-id="currentBindDevice.deptId"
      @success="handleBindSceneSuccess"
    />
  </el-card>
</template>

<style scoped lang="scss">
.device-list-container {
  padding: 20px 0;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.device-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.device-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.device-info {
  display: flex;
  margin-bottom: 16px;
  flex: 1;
}

.device-image {
  width: 80px;
  height: 80px;
  margin-right: 16px;
  flex-shrink: 0;
}

.device-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.device-details {
  flex: 1;
  min-width: 0;
}

.device-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.device-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px;
  margin-bottom: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.meta-label {
  color: #606266;
  margin-right: 4px;
}

.meta-value {
  color: #303133;
}

.status-online {
  color: #409eff;
}

.status-offline {
  color: #909399;
}

.device-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
